﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Text;

namespace Out2Share
{
    public static class XmlExtensions
    {
        #region internal class XmlTranslator

        internal class XmlTranslator
        {
            private readonly StringBuilder _xmlTextBuilder;
            private readonly XmlWriter _writer;

            private XmlTranslator()
            {
                _xmlTextBuilder = new StringBuilder();

                _writer = new XmlTextWriter(new StringWriter(_xmlTextBuilder))
                {
                    Formatting = Formatting.Indented,
                    Indentation = 2
                };
            }

            public XmlTranslator(XNode e)
                : this()
            {
                e.WriteTo(_writer);
            }

            public XmlTranslator(XmlNode e)
                : this()
            {
                e.WriteTo(_writer);
            }

            public XElement CreateXElement()
            {
                return XElement.Load(new StringReader(_xmlTextBuilder.ToString()));
            }

            public XDocument CreateXDocument()
            {
                return XDocument.Load(new StringReader(_xmlTextBuilder.ToString()));
            }

            public XmlElement CreateXmlElement()
            {
                return CreateXmlDocument().DocumentElement;
            }

            public XmlDocument CreateXmlDocument()
            {
                var doc = new XmlDocument();
                doc.Load(new XmlTextReader(new StringReader(_xmlTextBuilder.ToString())));
                return doc;
            }
        }

        #endregion

        public static XmlElement ToXmlElement(XElement xEl)
        {
            return new XmlTranslator(xEl).CreateXmlElement();
        }

        public static XmlDocument ToXmlDocument(XDocument xDoc)
        {
            return new XmlTranslator(xDoc).CreateXmlDocument();
        }

        public static XElement ToXElement(XmlElement xmlEl)
        {
            return new XmlTranslator(xmlEl).CreateXElement();
        }

        public static XDocument ToXDocument(XmlDocument xmlDoc)
        {
            return new XmlTranslator(xmlDoc).CreateXDocument();
        }
    }

}

